// routes/buses.ts
import express from 'express';
import { BusService } from '../../service';
import type { BusData } from '../../types/DataTypes';

const router = express.Router();

// 获取所有巴士
router.get('/', async (req, res) => {
    try {
        const buses = await BusService.getAllBuses();
        res.json({
            success: true,
            data: buses,
            count: buses.length
        });
    } catch (error) {
        console.error('获取巴士列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取巴士列表失败'
        });
    }
});

// 根据位置搜索巴士
router.get('/search', async (req, res) => {
    try {
        const { location } = req.query;

        if (!location || typeof location !== 'string') {
            return res.status(400).json({
                success: false,
                message: '请输入搜索位置'
            });
        }

        const buses = await BusService.searchBusesByLocation(location);
        res.json({
            success: true,
            data: buses,
            count: buses.length
        });
    } catch (error) {
        console.error('搜索巴士失败:', error);
        res.status(500).json({
            success: false,
            message: '搜索巴士失败'
        });
    }
});

// 添加新巴士
router.post('/', async (req, res) => {
    try {
        const { location, price, totalBus, availBus }: BusData = req.body;

        // 验证必填字段
        if (!location || price<0 || totalBus<=0) {
            console.log(typeof price)
            return res.status(400).json({
                success: false,
                message: '输入参数错误'
            });
        }

        const busData: BusData = {
            location,
            price: Number(price),
            totalBus: Number(totalBus),
            availBus: availBus !== undefined ? Number(availBus) : Number(totalBus)
        };

        const success = await BusService.addBus(busData);

        if (success) {
            res.status(201).json({
                success: true,
                message: '巴士添加成功',
                data: busData
            });
        } else {
            res.status(500).json({
                success: false,
                message: '巴士添加失败'
            });
        }
    } catch (error: any) {
        console.error('添加巴士失败:', error);

        if (error.message.includes('已存在')) {
            res.status(409).json({
                success: false,
                message: error.message
            });
        } else {
            res.status(500).json({
                success: false,
                message: '添加巴士失败'
            });
        }
    }
});

// 更新巴士信息
router.put('/update', async (req, res) => {
    try {
        const busData: BusData = req.body;

        // 验证更新字段
        // if (Object.keys(updates).length === 0) {
        //     return res.status(400).json({
        //         success: false,
        //         message: '请提供要更新的字段'
        //     });
        // }

        const success = await BusService.updateBus(busData);

        if (success) {
            res.json({
                success: true,
                message: '巴士信息更新成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '巴士不存在或更新失败'
            });
        }
    } catch (error) {
        console.error('更新巴士信息失败:', error);
        res.status(500).json({
            success: false,
            message: '更新巴士信息失败'
        });
    }
});

// 巴士可用数量+1
router.patch('/:location/increment', async (req, res) => {
    try {
        const { location } = req.params;

        const success = await BusService.incrementBusAvailability(location);

        if (success) {
            res.json({
                success: true,
                message: '巴士可用数量+1成功'
            });
        } else {
            res.status(400).json({
                success: false,
                message: '巴士不存在或可用数量已达上限'
            });
        }
    } catch (error) {
        console.error('增加巴士可用数量失败:', error);
        res.status(500).json({
            success: false,
            message: '增加巴士可用数量失败'
        });
    }
});

// 巴士可用数量-1
router.patch('/:location/decrement', async (req, res) => {
    try {
        const { location } = req.params;

        const success = await BusService.decrementBusAvailability(location);

        if (success) {
            res.json({
                success: true,
                message: '巴士可用数量-1成功'
            });
        } else {
            res.status(400).json({
                success: false,
                message: '巴士不存在或可用数量已为0'
            });
        }
    } catch (error) {
        console.error('减少巴士可用数量失败:', error);
        res.status(500).json({
            success: false,
            message: '减少巴士可用数量失败'
        });
    }
});

// 删除巴士
router.delete('/:location', async (req, res) => {
    try {
        const { location } = req.params;

        const success = await BusService.deleteBus(location);

        if (success) {
            res.json({
                success: true,
                message: '巴士删除成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '巴士不存在或删除失败'
            });
        }
    } catch (error) {
        console.error('删除巴士失败:', error);
        res.status(500).json({
            success: false,
            message: '删除巴士失败'
        });
    }
});

export default router;